use hound::{SampleFormat, WavSpec, WavWriter};
use tokio::fs;

#[flutter_rust_bridge::frb(init)]
pub fn init_app() {
    // Default utilities - feel free to customize
    flutter_rust_bridge::setup_default_user_utils();
}

const SAMPLE_RATE: u32 = 24_000;
const CHANNELS: u16 = 1;
const BITS_PER_SAMPLE: u16 = 16;

/// silk文件解码
#[flutter_rust_bridge::frb(dart_async)]
pub async fn silk_decode(silk_path: String, pcm_path: String) -> anyhow::Result<()> {
    let bytes = fs::read(silk_path).await?;
    let decode = silk_rs::decode_silk(bytes, SAMPLE_RATE as i32)?;
    fs::write(pcm_path, decode).await?;
    Ok(())
}

/// 删除文件或目录
#[flutter_rust_bridge::frb(dart_async)]
pub async fn delete_file_path(path: String) -> anyhow::Result<()> {
    let metadata = fs::metadata(&path).await?;
    if metadata.is_dir() {
        fs::remove_dir_all(&path).await?;
    } else {
        fs::remove_file(&path).await?
    }
    Ok(())
}

/// pcm转wav
#[flutter_rust_bridge::frb(dart_async)]
pub async fn pcm_2_wav(pcm_path: String, wav_path: String) -> anyhow::Result<()> {
    // 读取 PCM 文件
    let pcm_data = fs::read(pcm_path).await?;
    // 设置 WAV 文件的规格
    let spec = WavSpec {
        channels: CHANNELS,
        sample_rate: SAMPLE_RATE,
        sample_format: SampleFormat::Int, // 假设 PCM 数据是整型
        bits_per_sample: BITS_PER_SAMPLE,              // 假设每个样本是 16 位
    };
    // 创建 WAV 文件
    let mut writer = WavWriter::create(wav_path, spec)?;
    let chunk_size = 2usize;
    // 将 PCM 数据写入 WAV 文件
    for chunk in pcm_data.chunks(chunk_size) {
        // 16-bit per sample, 所以每个样本是 2 字节
        if chunk.len() == chunk_size {
            // 假设数据是小端序格式
            let sample = i16::from_le_bytes([chunk[0], chunk[1]]);
            writer.write_sample(sample)?;
        }
    }
    Ok(())
}
